package org.CurrencyService;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;

import org.CurrencyDAO.DTO.CurrencyExchangeDTO;
import org.CurrencyDAO.DTO.CurrencyType;
import org.CurrencyService.exception.CurrencyExchangeException;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;

public class XMLParser {

	private String childerNode = "pozycja";
	private String converterNode = "przelicznik";
	private String averageNode = "kurs_sredni";
	private String currencyCode = "kod_waluty";

	public CurrencyExchangeDTO parseXML(String fileName, CurrencyType currencyType) {
		SAXBuilder jdomBuilder = new SAXBuilder();
		try {
			Document jdomDocument = jdomBuilder.build(fileName);
			Element rss = jdomDocument.getRootElement();
			List<Element> channel = rss.getChildren(childerNode);
			for (Element element : channel) {
				if (element.getChildText(currencyCode).equalsIgnoreCase(currencyType.getCurrencyCode())) {
					CurrencyExchangeDTO createCurrencyWrapper = createCurrencyExchangeDTO(element);
					createCurrencyWrapper.setCurrencyType(currencyType);
					return createCurrencyWrapper;
				}
			}
		} catch (IOException exception) {
			throw new CurrencyExchangeException("Blad parsowania pliku xml");
		} catch (JDOMException exception) {
			throw new CurrencyExchangeException("Blad parsowania pliku xml");
		}

		return null;
	}

	private CurrencyExchangeDTO createCurrencyExchangeDTO(Element currency) {
		if (currency != null) {
			CurrencyExchangeDTO currencyTmp = new CurrencyExchangeDTO();
			currencyTmp.setConverter(Integer.parseInt(currency.getChildText(converterNode)));
			String averageText = currency.getChildText(averageNode);
			BigDecimal average = getBigDecimalFromString(averageText);
			if (average != null) {
				currencyTmp.setAverageExchange(average);
			}
			return currencyTmp;
		}
		return null;
	}

	private BigDecimal getBigDecimalFromString(String text) {
		if (text != null) {
			return new BigDecimal(text.replace(",", "."));
		}
		return null;
	}

}
